﻿using KPIS.GERP.GAMS.APP.App_UI.Commons;
using KPIS.GERP.GAMS.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.GAMS.APP.App_UI.Forms
{
    public partial class ReportIncomeStatement : System.Web.UI.Page
    {
        Commons.Main main = new Commons.Main();
        D_ACM_MAS_FISCAL_Period d_acm_fiscal_period = new D_ACM_MAS_FISCAL_Period();
        D_BGM_MAS_Source source = new D_BGM_MAS_Source();
        D_ACM_GENERAL_Ledger lg = new D_ACM_GENERAL_Ledger();
        MailMerge mailMerge = new MailMerge();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtBgmYear.Text = source.GetCurrentBgmYear();
                LoadGrdBgmSource();
            }
        }

        protected void LoadGrdBgmSource()
        {
            grdBgmSource.DataSource = source.GetList();
            grdBgmSource.DataBind();
        }

        protected void btnReportExcel_Click(object sender, EventArgs e)
        {
            string strBgmSourceSeq = "";

            if (!dpDate.GetDateValue().HasValue || string.IsNullOrEmpty(txtBgmYear.Text))
            {
                lblWarning.Visible = true;
                return;
            }

            if (grdBgmSource.SelectedItems.Count == 0)
            {
                lblWarning.Visible = true;
                return;
            }
            else
            {
                for (int i = 0; i < grdBgmSource.SelectedItems.Count; i++)
                {
                    GridDataItem item = (GridDataItem)grdBgmSource.SelectedItems[i];
                    strBgmSourceSeq += item["bgm_source_seq"].Text + (i == grdBgmSource.SelectedItems.Count - 1 ? "" : ",");
                }
            }

            lblWarning.Visible = false;
            DateTime date = dpDate.GetDateValue().Value;
            int nBgmYear = main.ConvertNullInt(txtBgmYear.Text) ?? DateTime.Today.Year;

            DataTable dtb = lg.ReportGrouping(date, nBgmYear, "'4', '5', '6'", strBgmSourceSeq);
            //DataTable dtb2 = lg.ReportGrouping(date, nBgmYear, "'4', '5'");//, strBgmSourceSeq, strAccountSeq, strAccountSeq2);
            Dictionary<string, string> dic = new Dictionary<string, string>();

            dic.Add("B1", DateTime.Now.ToShortDateString() + "  " + DateTime.Now.ToShortTimeString());
            dic.Add("A4", "ณ วันที่ " + date.ToLongDateString());

            int row = 6;
            int nSheet = 1;
            string strOldHead = "";
            string strOldHead2 = "";
            double SumAmount = 0;
            double SumAmount2 = 0;
            int nRowDtls = 1;

            for (int i = 0; i < dtb.Rows.Count; i++)
            {
                DataRow dr = dtb.Rows[i];
                string strHead = dr["head"].ToString();
                string strHead2 = dr["head2"].ToString();
                double dAmount = main.ConvertNullDouble(dr["amount"]) ?? 0;

                // footer2
                if (strOldHead2 != strHead2 && i > 0)
                {
                    dic.Add("A" + (row), "รวม" + GetHeadName2(strOldHead2));
                    dic.Add("D" + (row), SumAmount2.ToString("#,##0.00"));
                    row++;
                }

                // footer
                if (strOldHead != strHead && i > 0 && !string.IsNullOrEmpty(GetHeadName(strOldHead)))
                {
                    dic.Add("A" + (row), "รวม" + GetHeadName(strOldHead));
                    dic.Add("D" + (row), SumAmount.ToString("#,##0.00"));
                    row++;
                }

                // head
                if (strOldHead != strHead)
                {
                    if (!string.IsNullOrEmpty(GetHeadName(strHead)))
                    {
                        dic.Add("A" + row, GetHeadName(strHead));
                    }

                    strOldHead = strHead;
                    SumAmount = 0;
                    row++;
                }

                // head2
                if (strOldHead2 != strHead2)
                {
                    dic.Add("A" + row, GetHeadName2(strHead2));
                    strOldHead2 = strHead2;
                    SumAmount2 = 0;
                    row++;
                }

                // body
                dic.Add("B" + row, dr["grouping_name"].ToString());
                dic.Add("C" + row, nSheet.ToString());
                dic.Add("D" + row, dAmount.ToString("#,##0.00"));
                row++;

                var detail = lg.ReportGroupingDetail(dr["grouping_name"].ToString(), nBgmYear, date, strBgmSourceSeq);
                double sumDetail = 0;
                double sumDetailSub = 0;
                string strBgmSourceSeqOld = "";
                string strBgmSourceNameOld = "";
                string sheetName = "รายละเอียด";

                dic.Add(sheetName + "!A" + nRowDtls.ToString(), "(" + nSheet + ") รายละเอียด " + dr["grouping_name"].ToString());
                nRowDtls++;
                dic.Add(sheetName + "!A" + nRowDtls.ToString(), "รหัสบัญชี");
                dic.Add(sheetName + "!B" + nRowDtls.ToString(), "ชื่อบัญชี");
                dic.Add(sheetName + "!C" + nRowDtls.ToString(), "จำนวน(บาท)");
                nRowDtls++;

                for (int j = 0; j < detail.Rows.Count; j++)
                {
                    DataRow drDetail = detail.Rows[j];

                    if (strBgmSourceSeqOld != drDetail["bgm_source_seq"].ToString())
                    {
                        if (j > 0)
                        {
                            dic.Add(sheetName + "!A" + nRowDtls.ToString(), "รวม " + strBgmSourceNameOld);
                            dic.Add(sheetName + "!C" + nRowDtls.ToString(), sumDetailSub.ToString("#,##0.00"));
                            nRowDtls++;
                        }

                        dic.Add(sheetName + "!A" + nRowDtls.ToString(), drDetail["bgm_source_name"].ToString());
                        strBgmSourceSeqOld = drDetail["bgm_source_seq"].ToString();
                        strBgmSourceNameOld = drDetail["bgm_source_name"].ToString();
                        sumDetailSub = 0;
                        nRowDtls++;
                    }

                    dic.Add(sheetName + "!A" + nRowDtls.ToString(), drDetail["account_code"].ToString());
                    //dic.Add(nSheet.ToString() + "!B" + nRowDtls.ToString(), drDetail["gfmis_code"].ToString());
                    dic.Add(sheetName + "!B" + nRowDtls.ToString(), drDetail["account_name"].ToString());
                    dic.Add(sheetName + "!C" + nRowDtls.ToString(), (main.ConvertNullDouble(drDetail["amount"]) ?? 0).ToString("#,##0.00"));
                    sumDetail += main.ConvertNullDouble(drDetail["amount"]) ?? 0;
                    sumDetailSub += main.ConvertNullDouble(drDetail["amount"]) ?? 0;
                    nRowDtls++;

                    if (j == detail.Rows.Count - 1)
                    {
                        dic.Add(sheetName + "!A" + nRowDtls.ToString(), "รวม " + strBgmSourceNameOld);
                        dic.Add(sheetName + "!C" + nRowDtls.ToString(), sumDetailSub.ToString("#,##0.00"));
                        nRowDtls++;
                    }
                }

                dic.Add(sheetName + "!B" + nRowDtls.ToString(), "รวม");
                dic.Add(sheetName + "!C" + nRowDtls.ToString(), sumDetail.ToString("#,##0.00"));

                nRowDtls++;
                nRowDtls++;
                nSheet++;

                SumAmount += dAmount;
                //if (strHead == "1") SumAmount1 += dAmount;
                SumAmount2 += dAmount;

                if (i == dtb.Rows.Count - 1)
                {
                    dic.Add("A" + (row), "รวม" + GetHeadName2(strHead2));
                    dic.Add("D" + (row), SumAmount2.ToString("#,##0.00"));

                    if (!string.IsNullOrEmpty(GetHeadName(strHead)))
                    {
                        row++;
                        dic.Add("A" + (row), "รวม" + GetHeadName(strHead));
                        dic.Add("D" + (row), SumAmount.ToString("#,##0.00"));
                    }
                }
            }

            double dSumIncomeAndExpense = 0;

            foreach (DataRow dr in dtb.Rows)
            {
                dSumIncomeAndExpense += main.ConvertNullInt(dr["head"]) == 4 ? (main.ConvertNullDouble(dr["amount"]) ?? 0) : (- main.ConvertNullDouble(dr["amount"]) ?? 0);
            }

            row++;
            dic.Add("A" + (row), "รายได้สูง(ต่ำ)กว่าค่าใช้จ่าย (ปีปัจจุบัน)");
            dic.Add("D" + (row), dSumIncomeAndExpense.ToString("#,##0.00"));

            mailMerge.MergeExcel(Response, Server.MapPath("~/Reports/Templates/IncomeStatement.xlsx"), string.Format("IncomeStatement{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), null, dic, null, "template");
        }

        protected string GetHeadName(string strHead)
        {
            string strHeadName = "";

            switch (strHead)
            {
                case "1":
                    strHeadName = "สินทรัพย์";
                    break;
                case "2":
                    strHeadName = "หนี้สิน";
                    break;
                case "3":
                    //dic.Add("A" + row, "ส่วนทุน");
                    break;
                case "4":
                    strHeadName = "รายได้";
                    break;
                case "5":
                    //dic.Add("A" + row, "ค่าใช้จ่าย");
                    break;
            }

            return strHeadName;
        }

        protected string GetHeadName2(string strHead2)
        {
            string strHeadName = "";

            switch (strHead2)
            {
                case "11":
                    strHeadName = "สินทรัพย์หมุนเวียน";
                    break;
                case "12":
                    strHeadName = "สินทรัพย์ไม่หมุนเวียน";
                    break;
                case "21":
                    strHeadName = "หนี้สินหมุนเวียน";
                    break;
                case "22":
                    strHeadName = "หนี้สินไม่หมุนเวียน";
                    break;
                case "31":
                    strHeadName = "สินทรัพย์สุทธิ/ส่วนทุน";
                    break;
                case "41":
                    strHeadName = "รายได้จากรัฐบาล";
                    break;
                case "42":
                    strHeadName = "รายได้จากแหล่งอื่น";
                    break;
                case "51":
                    strHeadName = "ค่าใช้จ่ายจากการดำเนินงาน";
                    break;
            }

            return strHeadName;
        }
    }
}